// utils/storage.ts
import AsyncStorage from '@react-native-async-storage/async-storage';

export const storage = {
  // 存储数据
  set: async <T>(key: string, value: T): Promise<void> => {
    try {
      const jsonValue = JSON.stringify(value);
      await AsyncStorage.setItem(key, jsonValue);
    } catch (e) {
      console.error(`存储失败: ${key}`, e);
    }
  },

  // 读取数据
  get: async <T>(key: string): Promise<T | null> => {
    try {
      const jsonValue = await AsyncStorage.getItem(key);
      return jsonValue ? JSON.parse(jsonValue) : null;
    } catch (e) {
      console.error(`读取失败: ${key}`, e);
      return null;
    }
  },

  // 删除数据
  remove: async (key: string): Promise<void> => {
    await AsyncStorage.removeItem(key);
  },

  // 清空全部
  clear: async (): Promise<void> => {
    await AsyncStorage.clear();
  }
};